package com.petdog.module.community.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.petdog.infrastructure.entity.Community;
import com.petdog.infrastructure.entity.UserCommunity;
import com.petdog.infrastructure.mapper.CommunityMapper;
import com.petdog.infrastructure.mapper.UserCommunityMapper;
import com.petdog.module.community.dto.JoinCommunityRequest;
import com.petdog.module.community.dto.CommunityMemberResponse;
import com.petdog.module.community.service.UserCommunityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.apache.commons.lang3.StringUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户社区关联服务实现类
 */
@Service
public class UserCommunityServiceImpl implements UserCommunityService {
    
    @Autowired
    private UserCommunityMapper userCommunityMapper;
    
    @Autowired
    private CommunityMapper communityMapper;
    
    @Override
    public boolean joinCommunity(JoinCommunityRequest request) {
        // 参数验证
        if (request.getUserId() == null || request.getUserId() <= 0) {
            throw new IllegalArgumentException("用户ID无效");
        }
        
        if (request.getCommunityId() == null || request.getCommunityId() <= 0) {
            throw new IllegalArgumentException("社区ID无效");
        }
        
        // 检查社区是否存在且状态正常
        Community community = communityMapper.selectById(request.getCommunityId());
        if (community == null) {
            throw new SecurityException("社区不存在");
        }
        
        if (community.getStatus() != 1) { // 1表示正常状态
            throw new SecurityException("该社区已被冻结，无法加入");
        }
        
        // 检查用户是否已加入社区
        UserCommunity existing = getUserRoleInCommunity(request.getUserId(), request.getCommunityId());
        if (existing != null) {
            return false; // 用户已在社区中
        }
        
        // 创建新的用户社区关联
        UserCommunity userCommunity = new UserCommunity();
        userCommunity.setUserId(request.getUserId());
        userCommunity.setCommunityId(request.getCommunityId());
        userCommunity.setRole(1); // 默认角色为普通成员
        userCommunity.setStatus(1); // 状态为正常
        userCommunity.setJoinTime(LocalDateTime.now());
        userCommunity.setLastActiveTime(LocalDateTime.now());
        
        boolean success = userCommunityMapper.insert(userCommunity) > 0;
        
        // 如果加入成功，更新社区成员数量
        if (success) {
            updateCommunityMemberCount(request.getCommunityId(), true);
        }
        
        return success;
    }
    
    @Override
    public boolean leaveCommunity(Long userId, Long communityId) {
        // 参数验证
        if (userId == null || userId <= 0) {
            throw new IllegalArgumentException("用户ID无效");
        }
        
        if (communityId == null || communityId <= 0) {
            throw new IllegalArgumentException("社区ID无效");
        }
        
        // 检查社区是否存在
        Community community = communityMapper.selectById(communityId);
        if (community == null) {
            throw new SecurityException("社区不存在");
        }
        
        // 检查用户是否为社区创建者
        UserCommunity userCommunity = getUserRoleInCommunity(userId, communityId);
        if (userCommunity == null) {
            throw new SecurityException("您尚未加入该社区");
        }
        
        if (userCommunity.getRole() == 3) { // 3表示创建者角色
            throw new SecurityException("创建者不能退出社区");
        }
        
        boolean success = userCommunityMapper.deleteByUserIdAndCommunityId(userId, communityId) > 0;
        
        // 如果退出成功，更新社区成员数量
        if (success) {
            updateCommunityMemberCount(communityId, false);
        }
        
        return success;
    }
    
    /**
     * 更新社区成员数量
     * @param communityId 社区ID
     * @param isIncrease 是否增加成员数量
     */
    private void updateCommunityMemberCount(Long communityId, boolean isIncrease) {
        Map<String, Object> params = new HashMap<>();
        params.put("communityId", communityId);
        
        // 获取当前社区成员数量
        int currentCount = getCommunityMemberCount(communityId);
        
        // 计算新的成员数量
        int newCount = isIncrease ? currentCount + 1 : Math.max(0, currentCount - 1);
        
        communityMapper.updateMemberCount(communityId, newCount);
    }
    
    @Override
    public List<CommunityMemberResponse> getCommunityMembers(Long communityId, int page, int pageSize) {
        // 这里需要实现分页查询社区成员列表的逻辑
        // 实际项目中，可能需要联合查询用户表获取用户信息
        // 暂时返回空列表
        return List.of();
    }
    
    @Override
    public UserCommunity getUserRoleInCommunity(Long userId, Long communityId) {
        return userCommunityMapper.selectByUserIdAndCommunityId(userId, communityId);
    }
    
    @Override
    public boolean updateUserRole(Long userId, Long communityId, Integer role) {
        UserCommunity userCommunity = getUserRoleInCommunity(userId, communityId);
        if (userCommunity == null) {
            return false;
        }
        
        userCommunity.setRole(role);
        return userCommunityMapper.updateById(userCommunity) > 0;
    }
    
    @Override
    public int getCommunityMemberCount(Long communityId) {
        QueryWrapper<UserCommunity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("community_id", communityId)
                   .eq("status", 1);
        return userCommunityMapper.selectCount(queryWrapper).intValue();
    }
    
    @Override
    public boolean isCommunityAdmin(Long userId, Long communityId) {
        UserCommunity userCommunity = getUserRoleInCommunity(userId, communityId);
        return userCommunity != null && (userCommunity.getRole() == 2 || userCommunity.getRole() == 3);
    }
}